{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 加载数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pandas import DataFrame\n",
    "from pandas import concat\n",
    "\n",
    "def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\n",
    "\t\"\"\"\n",
    "\tFrame a time series as a supervised learning dataset.\n",
    "\tArguments:\n",
    "\t\tdata: Sequence of observations as a list or NumPy array.\n",
    "\t\tn_in: Number of lag observations as input (X).\n",
    "\t\tn_out: Number of observations as output (y).\n",
    "\t\tdropnan: Boolean whether or not to drop rows with NaN values.\n",
    "\tReturns:\n",
    "\t\tPandas DataFrame of series framed for supervised learning.\n",
    "\t\"\"\"\n",
    "\tn_vars = 1 if type(data) is list else data.shape[1]\n",
    "\tdf = DataFrame(data)\n",
    "\tcols, names = list(), list()\n",
    "\t# input sequence (t-n, ... t-1)\n",
    "\tfor i in range(n_in, 0, -1):\n",
    "\t\tcols.append(df.shift(i))\n",
    "\t\tnames += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\n",
    "\t# forecast sequence (t, t+1, ... t+n)\n",
    "\tfor i in range(0, n_out):\n",
    "\t\tcols.append(df.shift(-i))\n",
    "\t\tif i == 0:\n",
    "\t\t\tnames += [('var%d(t)' % (j+1)) for j in range(n_vars)]\n",
    "\t\telse:\n",
    "\t\t\tnames += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\n",
    "\t# put it all together\n",
    "\tagg = concat(cols, axis=1)\n",
    "\tagg.columns = names\n",
    "\t# drop rows with NaN values\n",
    "\tif dropnan:\n",
    "\t\tagg.dropna(inplace=True)\n",
    "\treturn agg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
      "   var1(t-4)  var1(t-3)  var1(t-2)  var1(t-1)  var1(t)\n",
      "4        0.0        1.0        2.0        3.0        4\n",
      "5        1.0        2.0        3.0        4.0        5\n",
      "6        2.0        3.0        4.0        5.0        6\n",
      "7        3.0        4.0        5.0        6.0        7\n",
      "8        4.0        5.0        6.0        7.0        8\n",
      "9        5.0        6.0        7.0        8.0        9\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "(6, 5)\n"
     ]
    }
   ],
   "source": [
    "values = [x for x in range(10)]\n",
    "print(values)\n",
    "data = series_to_supervised(values, 4, 1)\n",
    "print(data)\n",
    "print(type(data))\n",
    "print(data.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   var1(t-4)  var1(t-3)  var1(t-2)  var1(t-1)\n",
      "4        0.0        1.0        2.0        3.0\n",
      "5        1.0        2.0        3.0        4.0\n",
      "6        2.0        3.0        4.0        5.0\n",
      "7        3.0        4.0        5.0        6.0\n",
      "8        4.0        5.0        6.0        7.0\n",
      "9        5.0        6.0        7.0        8.0\n",
      "=============================\n",
      "4    4\n",
      "5    5\n",
      "6    6\n",
      "7    7\n",
      "8    8\n",
      "9    9\n",
      "Name: var1(t), dtype: int64\n",
      "[[[0.]\n",
      "  [1.]\n",
      "  [2.]\n",
      "  [3.]]\n",
      "\n",
      " [[1.]\n",
      "  [2.]\n",
      "  [3.]\n",
      "  [4.]]\n",
      "\n",
      " [[2.]\n",
      "  [3.]\n",
      "  [4.]\n",
      "  [5.]]\n",
      "\n",
      " [[3.]\n",
      "  [4.]\n",
      "  [5.]\n",
      "  [6.]]\n",
      "\n",
      " [[4.]\n",
      "  [5.]\n",
      "  [6.]\n",
      "  [7.]]\n",
      "\n",
      " [[5.]\n",
      "  [6.]\n",
      "  [7.]\n",
      "  [8.]]]\n",
      "(6, 4, 1)\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "处理数据\n",
    "'''\n",
    "train_x = data.iloc[:,:-1]#除了最后一列不要,代码还可以更加完善可读性高\n",
    "train_y = data.iloc[:,-1]\n",
    "print(train_x)\n",
    "print(\"=============================\")\n",
    "print(train_y)\n",
    "train_x = train_x.values#values才能reshape，否则AttributeError: 'DataFrame' object has no attribute 'reshape'\n",
    "# train_x = train_x.reshape((train_x.shape[0], 1, train_x.shape[1]))#[hang,1,column]适合一个时间步多个变量也就是多个feature的打法\n",
    "train_x = train_x.reshape(train_x.shape[0], train_x.shape[1], 1)#适合多个时间步单个变量也就是单个feature的打法\n",
    "# train_y = train_x.reshape((train_x.shape[0], 1, train_x.shape[1]))\n",
    "\n",
    "print(train_x)\n",
    "print(train_x.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy\n",
    "import matplotlib.pyplot as plt\n",
    "from keras.models import Sequential\n",
    "from keras.layers import Dense\n",
    "from keras.layers import LSTM\n",
    "import  pandas as pd\n",
    "import  os\n",
    "from keras.models import Sequential, load_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mkdir(path):\n",
    "    # 引入模块\n",
    "    import os\n",
    " \n",
    "    # 去除首位空格\n",
    "    path=path.strip()\n",
    "    # 去除尾部 \\ 符号\n",
    "    path=path.rstrip(\"\\\\\")\n",
    " \n",
    "    # 判断路径是否存在\n",
    "    # 存在     True\n",
    "    # 不存在   False\n",
    "    isExists=os.path.exists(path)\n",
    " \n",
    "    # 判断结果\n",
    "    if not isExists:\n",
    "        # 如果不存在则创建目录\n",
    "        # 创建目录操作函数\n",
    "        os.makedirs(path) \n",
    " \n",
    "        print (path+' 创建成功')\n",
    "        return True\n",
    "    else:\n",
    "        # 如果目录存在则不创建，并提示目录已存在\n",
    "        print (path+' 目录已存在')\n",
    "        return False\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "conv1d_34 (Conv1D)           (None, 4, 128)            512       \n",
      "_________________________________________________________________\n",
      "batch_normalization_22 (Batc (None, 4, 128)            512       \n",
      "_________________________________________________________________\n",
      "activation_36 (Activation)   (None, 4, 128)            0         \n",
      "_________________________________________________________________\n",
      "conv1d_35 (Conv1D)           (None, 3, 256)            65792     \n",
      "_________________________________________________________________\n",
      "batch_normalization_23 (Batc (None, 3, 256)            1024      \n",
      "_________________________________________________________________\n",
      "activation_37 (Activation)   (None, 3, 256)            0         \n",
      "_________________________________________________________________\n",
      "time_distributed_14 (TimeDis (None, 3, 1)              257       \n",
      "_________________________________________________________________\n",
      "dropout_14 (Dropout)         (None, 3, 1)              0         \n",
      "_________________________________________________________________\n",
      "flatten_3 (Flatten)          (None, 3)                 0         \n",
      "_________________________________________________________________\n",
      "dense_18 (Dense)             (None, 1)                 4         \n",
      "_________________________________________________________________\n",
      "activation_38 (Activation)   (None, 1)                 0         \n",
      "=================================================================\n",
      "Total params: 68,101\n",
      "Trainable params: 67,333\n",
      "Non-trainable params: 768\n",
      "_________________________________________________________________\n",
      "Epoch 1/100\n",
      " - 1s - loss: 36.8854\n",
      "Epoch 2/100\n",
      " - 0s - loss: 33.2522\n",
      "Epoch 3/100\n",
      " - 0s - loss: 35.0057\n",
      "Epoch 4/100\n",
      " - 0s - loss: 34.9081\n",
      "Epoch 5/100\n",
      " - 0s - loss: 35.6223\n",
      "Epoch 6/100\n",
      " - 0s - loss: 34.5215\n",
      "Epoch 7/100\n",
      " - 0s - loss: 35.9362\n",
      "Epoch 8/100\n",
      " - 0s - loss: 34.3939\n",
      "Epoch 9/100\n",
      " - 0s - loss: 34.1941\n",
      "Epoch 10/100\n",
      " - 0s - loss: 33.1971\n",
      "Epoch 11/100\n",
      " - 0s - loss: 34.5569\n",
      "Epoch 12/100\n",
      " - 0s - loss: 35.9706\n",
      "Epoch 13/100\n",
      " - 0s - loss: 36.5676\n",
      "Epoch 14/100\n",
      " - 0s - loss: 34.5391\n",
      "Epoch 15/100\n",
      " - 0s - loss: 34.0518\n",
      "Epoch 16/100\n",
      " - 0s - loss: 34.0493\n",
      "Epoch 17/100\n",
      " - 0s - loss: 34.4039\n",
      "Epoch 18/100\n",
      " - 0s - loss: 35.0861\n",
      "Epoch 19/100\n",
      " - 0s - loss: 34.7940\n",
      "Epoch 20/100\n",
      " - 0s - loss: 36.0002\n",
      "Epoch 21/100\n",
      " - 0s - loss: 35.6722\n",
      "Epoch 22/100\n",
      " - 0s - loss: 33.8686\n",
      "Epoch 23/100\n",
      " - 0s - loss: 33.8363\n",
      "Epoch 24/100\n",
      " - 0s - loss: 34.6796\n",
      "Epoch 25/100\n",
      " - 0s - loss: 33.4995\n",
      "Epoch 26/100\n",
      " - 0s - loss: 33.2020\n",
      "Epoch 27/100\n",
      " - 0s - loss: 34.4650\n",
      "Epoch 28/100\n",
      " - 0s - loss: 34.7856\n",
      "Epoch 29/100\n",
      " - 0s - loss: 33.9913\n",
      "Epoch 30/100\n",
      " - 0s - loss: 34.1611\n",
      "Epoch 31/100\n",
      " - 0s - loss: 34.1129\n",
      "Epoch 32/100\n",
      " - 0s - loss: 33.3090\n",
      "Epoch 33/100\n",
      " - 0s - loss: 34.6233\n",
      "Epoch 34/100\n",
      " - 0s - loss: 33.2044\n",
      "Epoch 35/100\n",
      " - 0s - loss: 33.9793\n",
      "Epoch 36/100\n",
      " - 0s - loss: 33.1791\n",
      "Epoch 37/100\n",
      " - 0s - loss: 33.3572\n",
      "Epoch 38/100\n",
      " - 0s - loss: 33.2877\n",
      "Epoch 39/100\n",
      " - 0s - loss: 33.1771\n",
      "Epoch 40/100\n",
      " - 0s - loss: 34.0465\n",
      "Epoch 41/100\n",
      " - 0s - loss: 33.2496\n",
      "Epoch 42/100\n",
      " - 0s - loss: 33.9948\n",
      "Epoch 43/100\n",
      " - 0s - loss: 34.5995\n",
      "Epoch 44/100\n",
      " - 0s - loss: 34.3602\n",
      "Epoch 45/100\n",
      " - 0s - loss: 33.6782\n",
      "Epoch 46/100\n",
      " - 0s - loss: 33.3215\n",
      "Epoch 47/100\n",
      " - 0s - loss: 34.5463\n",
      "Epoch 48/100\n",
      " - 0s - loss: 33.1761\n",
      "Epoch 49/100\n",
      " - 0s - loss: 33.2140\n",
      "Epoch 50/100\n",
      " - 0s - loss: 33.2309\n",
      "Epoch 51/100\n",
      " - 0s - loss: 33.2016\n",
      "Epoch 52/100\n",
      " - 0s - loss: 33.1715\n",
      "Epoch 53/100\n",
      " - 0s - loss: 33.2353\n",
      "Epoch 54/100\n",
      " - 0s - loss: 33.8550\n",
      "Epoch 55/100\n",
      " - 0s - loss: 34.8554\n",
      "Epoch 56/100\n",
      " - 0s - loss: 35.1157\n",
      "Epoch 57/100\n",
      " - 0s - loss: 33.2801\n",
      "Epoch 58/100\n",
      " - 0s - loss: 33.2117\n",
      "Epoch 59/100\n",
      " - 0s - loss: 33.1682\n",
      "Epoch 60/100\n",
      " - 0s - loss: 33.1956\n",
      "Epoch 61/100\n",
      " - 0s - loss: 35.4367\n",
      "Epoch 62/100\n",
      " - 0s - loss: 33.2134\n",
      "Epoch 63/100\n",
      " - 0s - loss: 33.1981\n",
      "Epoch 64/100\n",
      " - 0s - loss: 34.4807\n",
      "Epoch 65/100\n",
      " - 0s - loss: 34.4426\n",
      "Epoch 66/100\n",
      " - 0s - loss: 33.1680\n",
      "Epoch 67/100\n",
      " - 0s - loss: 35.5560\n",
      "Epoch 68/100\n",
      " - 0s - loss: 33.1924\n",
      "Epoch 69/100\n",
      " - 0s - loss: 33.1681\n",
      "Epoch 70/100\n",
      " - 0s - loss: 34.4365\n",
      "Epoch 71/100\n",
      " - 0s - loss: 33.1876\n",
      "Epoch 72/100\n",
      " - 0s - loss: 34.4672\n",
      "Epoch 73/100\n",
      " - 0s - loss: 33.1804\n",
      "Epoch 74/100\n",
      " - 0s - loss: 34.1218\n",
      "Epoch 75/100\n",
      " - 0s - loss: 34.9234\n",
      "Epoch 76/100\n",
      " - 0s - loss: 33.1978\n",
      "Epoch 77/100\n",
      " - 0s - loss: 33.1677\n",
      "Epoch 78/100\n",
      " - 0s - loss: 33.1932\n",
      "Epoch 79/100\n",
      " - 0s - loss: 34.2729\n",
      "Epoch 80/100\n",
      " - 0s - loss: 33.1667\n",
      "Epoch 81/100\n",
      " - 0s - loss: 33.1686\n",
      "Epoch 82/100\n",
      " - 0s - loss: 34.4210\n",
      "Epoch 83/100\n",
      " - 0s - loss: 34.9325\n",
      "Epoch 84/100\n",
      " - 0s - loss: 33.9738\n",
      "Epoch 85/100\n",
      " - 0s - loss: 33.9601\n",
      "Epoch 86/100\n",
      " - 0s - loss: 33.1667\n",
      "Epoch 87/100\n",
      " - 0s - loss: 34.5974\n",
      "Epoch 88/100\n",
      " - 0s - loss: 34.6160\n",
      "Epoch 89/100\n",
      " - 0s - loss: 33.1877\n",
      "Epoch 90/100\n",
      " - 0s - loss: 33.9557\n",
      "Epoch 91/100\n",
      " - 0s - loss: 33.6535\n",
      "Epoch 92/100\n",
      " - 0s - loss: 33.2047\n",
      "Epoch 93/100\n",
      " - 0s - loss: 35.0390\n",
      "Epoch 94/100\n",
      " - 0s - loss: 34.4151\n",
      "Epoch 95/100\n",
      " - 0s - loss: 34.1359\n",
      "Epoch 96/100\n",
      " - 0s - loss: 33.1667\n",
      "Epoch 97/100\n",
      " - 0s - loss: 34.2731\n",
      "Epoch 98/100\n",
      " - 0s - loss: 34.2465\n",
      "Epoch 99/100\n",
      " - 0s - loss: 33.1817\n",
      "Epoch 100/100\n",
      " - 0s - loss: 33.1842\n",
      "DATA 目录已存在\n"
     ]
    }
   ],
   "source": [
    "\n",
    "from keras.models import Sequential\n",
    "from keras.layers import Embedding,SimpleRNN\n",
    "from keras.layers import Dense, Dropout\n",
    "from keras.layers import GRU,Conv1D,Activation,GlobalAveragePooling1D,Flatten,TimeDistributed,Reshape\n",
    "from keras.layers.normalization import BatchNormalization\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "max_lenth = 10 #序列长度\n",
    "max_features = 4 #变量维度\n",
    "\n",
    "model = Sequential()\n",
    "model.add(Conv1D(128, 3, padding='same', input_shape=(train_x.shape[1], train_x.shape[2]))) # padding = 'same' 输出与输入序列长度一样，如果去掉，换成valid就是10-3+1=8\n",
    "model.add(BatchNormalization())\n",
    "model.add(Activation('relu'))\n",
    "model.add(Conv1D(256, 2))# output shape = (None,10-3+1,256)\n",
    "model.add(BatchNormalization())\n",
    "model.add(Activation('relu'))\n",
    "# model.add(Conv1D(128, 1))# output shape = (None,8-3+1,256)\n",
    "# model.add(BatchNormalization())\n",
    "# model.add(Activation('relu'))\n",
    "model.add(TimeDistributed(Dense(1)))\n",
    "# model.add(GlobalAveragePooling1D())   #时序的时间维度上全局池化 比如 x(t1),x(t2),...x(tn)，把它们相加并且取平均，这样就进行了降维，一个序列变成了一个值\n",
    "model.add(Dropout(0.5))\n",
    "model.add(Flatten())\n",
    "model.add(Dense(1))\n",
    "# model.add(TimeDistributed(Dense(1)))放这儿会出现问题，TimeDistributed只对（None,sequence,output_dim）这样格式的数据起作用，对（None,output_dim）不起作用\n",
    "model.add(Activation('sigmoid'))\n",
    "model.summary()\n",
    "model.compile(loss='mean_squared_error', optimizer='adam')\n",
    "model.fit(train_x, train_y, epochs=100, batch_size=1, verbose=2)\n",
    "mkpath=\"DATA\" #保存模型的路径\n",
    "mkdir(mkpath)#创造文件夹\n",
    "model.save(os.path.join(\"DATA\",\"Test\" + \".h5\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 不知道为什么不收敛"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[0.]\n",
      "  [1.]\n",
      "  [2.]\n",
      "  [3.]]\n",
      "\n",
      " [[1.]\n",
      "  [2.]\n",
      "  [3.]\n",
      "  [4.]]\n",
      "\n",
      " [[2.]\n",
      "  [3.]\n",
      "  [4.]\n",
      "  [5.]]\n",
      "\n",
      " [[3.]\n",
      "  [4.]\n",
      "  [5.]\n",
      "  [6.]]\n",
      "\n",
      " [[4.]\n",
      "  [5.]\n",
      "  [6.]\n",
      "  [7.]]\n",
      "\n",
      " [[5.]\n",
      "  [6.]\n",
      "  [7.]\n",
      "  [8.]]]\n",
      "===================\n",
      "[[0.]\n",
      " [1.]\n",
      " [2.]\n",
      " [3.]]\n",
      "===================\n",
      "[[0.41182756]]\n"
     ]
    }
   ],
   "source": [
    "print(train_x)\n",
    "print(\"===================\")\n",
    "print(train_x[0])\n",
    "\n",
    "predict_x = train_x[0].reshape(1, train_x.shape[1], 1)#shape=(1,seq_length,dim) sample=1 很好理解\n",
    "print(\"===================\")\n",
    "y_train_pred_nn = model.predict(predict_x)\n",
    "print(y_train_pred_nn)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "ea70d47c1026074199160e48050b9f1be75d4ba7d6f2081b88238ca77789226b"
  },
  "kernelspec": {
   "display_name": "Python 3.7.11 ('pytorch-gpu')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
